package com.caiheng.api.service.titlemenu.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.product.ProductMapper;
import com.caiheng.api.dao.titlemenu.TitleMenuMapper;
import com.caiheng.api.dao.titlemenu.TitleMenuSectionLinksMapper;
import com.caiheng.api.dao.titlemenu.TitleMenuSectionMapper;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.Coupons;
import com.caiheng.api.entity.product.Product;
import com.caiheng.api.entity.titlemenu.TitleMenu;
import com.caiheng.api.entity.titlemenu.TitleMenuSection;
import com.caiheng.api.entity.titlemenu.TitleMenuSectionCity;
import com.caiheng.api.entity.titlemenu.TitleMenuSectionLinks;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.platfom.CouponsService;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.mer.MerService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.service.titlemenu.TitleMenuSectionCityService;
import com.caiheng.api.service.titlemenu.TitleMenuSectionService;
import com.caiheng.api.util.ListUtil;
import com.caiheng.api.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class TitleMenuSectionServiceImpl extends BaseServiceImpl<TitleMenuSectionMapper, TitleMenuSection> implements TitleMenuSectionService {

    @Resource
    private TitleMenuSectionMapper titleMenuSectionMapper;
    @Resource
    private TitleMenuSectionLinksMapper titleMenuSectionLinksMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductService productService;
    @Resource
    private CouponsService couponsService;
    @Resource
    private MerService merService;
    @Resource
    private TitleMenuMapper titleMenuMapper;
    @Resource
    private TitleMenuSectionCityService sectionCityService;

    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址

    @Override
    public List<TitleMenuSection> selectByMenuDefault(User user, String platform,Integer pageIndex, Integer pageSize) {
        List<TitleMenuSection> sections = new ArrayList<>();
        List<TitleMenuSection> sectionsShow = new ArrayList<>();
        try{
            QueryWrapper<TitleMenu> qwMenu = new QueryWrapper<>();
            qwMenu.eq("menu_type",1);
            qwMenu.eq("is_default",1);
            qwMenu.last("limit 1");
            TitleMenu menuDefault = titleMenuMapper.selectOne(qwMenu);

            //2. 内容列表
            QueryWrapper<TitleMenuSection> qw = new QueryWrapper<>();
            qw.eq("state",0);
            if(menuDefault !=null && menuDefault.getId() > 0){
                qw.eq("title_menu_id",menuDefault.getId());
            }
            qw.orderByAsc("sort");
            sections = titleMenuSectionMapper.getPageEntityList(qw,pageIndex,pageSize);
            //3. 内容列表里的内容
            for(TitleMenuSection section: sections){
                if(StrUtil.isNotEmpty(section.getBgUrl())){
                    section.setBgUrl(imgPrefix + section.getBgUrl());
                }

                System.out.println("===========1  " + section.getTitleImgUrl());
                if(StrUtil.isNotEmpty(section.getTitleImgUrl())){
                    section.setTitleImgUrl(imgPrefix + section.getTitleImgUrl());
                    System.out.println("=========== imgPrefix 1  " + section.getTitleImgUrl());
                }

                if(section.getShowType() == 0){
                    int column = section.getColumnCount();
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    for (TitleMenuSectionLinks links : linkss){
                        links.setIsOpen(section.getIsOpen());
                        links.setLinkUrl("/pages/product/detail/index?id=" + links.getLinkId());
                        String img_key = links.getImgUrl() != null ? links.getImgUrl() : "";
                        if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("http") < 0){
                            links.setImgUrl(imgPrefix + img_key);
                        }else{
                            if(links.getLinkId()!=null){
                                Product product = productService.getProductInfoById(links.getLinkId(), 1);
                                links.setImgUrl(product.getImage());
                            }
                        }
//                链接的类型   product - 单商品 - page 商品页（title_menu_id）  group - 团购商品  coupon - 优惠券  image - 单图片 不跳转
                        if(links.getLinkType().equals("page")){//普通商品页
                            TitleMenu titleMenu = titleMenuMapper.selectById(links.getLinkId());
                            if(titleMenu != null){
                                img_key = titleMenu.getLinkLogo() != null ? titleMenu.getLinkLogo() : "";
                                if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("http") < 0){
                                    titleMenu.setLinkLogo(imgPrefix + img_key);
                                }
                            }
                        } else if(links.getLinkType().equals("product")){
                            Product product = productService.getProductInfoById(links.getLinkId(),1);
                            links.setProduct(product);
                        }

                        if(links.getLabelText() != null && !links.getLabelText().equals("")){
                            String[] lables = StringUtil.StrT0List(links.getLabelText(),",");
                            links.setLabelTexts(lables);
                        }
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                }
                else if(section.getShowType() == 1){// 子分类下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():10;
                    List<Product> products = productService.queryProductList("",null,section.getCateChildId(),platform, 1, showCount);
                    section.setProducts(products);
                } else if(section.getShowType() == 2){// 子分类下的商家列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():10;
                    //Integer cate_child_id, Integer offset, Integer pageSize, double longitude, double latitude
                    int offset = (pageIndex - 1) * pageSize;
                    List<Mer> mers = merService.selectBySection(section.getCateChildId(),offset, showCount,1, showCount);
                    section.setMers(mers);
                } else if(section.getShowType() == 3){// 单一商家下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount() : 10;
                    List<Product> products = productService.queryProductList(section.getMerId(), showCount);
                    section.setProducts(products);
                }
                //全区域  或者限定当前用户的城市
                TitleMenuSectionCity sectionCity = sectionCityService.getSectionCityByCityName(section.getId(),user);
                if(section.getIsAllCity() == 1 || (sectionCity != null)){
                    sectionsShow.add(section);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sectionsShow;
    }

    @Override
    public List<TitleMenuSection> selectBySectionByLocation(User user, Integer pageIndex, Integer pageSize, double lng, double lat,String platform) {
        List<TitleMenuSection> sections = new ArrayList<>();
        List<TitleMenuSection> sectionsShow = new ArrayList<>();
        try{
            QueryWrapper<TitleMenu> qwMenu = new QueryWrapper<>();
            qwMenu.eq("menu_type",1);
            qwMenu.eq("is_default",1);
            qwMenu.last("limit 1");
            qwMenu.orderByAsc("sort");
            TitleMenu menuDefault = titleMenuMapper.selectOne(qwMenu);

            //2. 内容列表
            QueryWrapper<TitleMenuSection> qw = new QueryWrapper<>();
            qw.eq("state",0);
            if(menuDefault!=null){
                qw.eq("title_menu_id",menuDefault.getId());
            }
            if(user != null && user.getIsTestUser() == 1){
                qw.eq("is_test", 1);
            }else{
                qw.eq("is_test", 0);
            }
            qw.orderByAsc("sort");
            sections = titleMenuSectionMapper.getPageEntityList(qw,pageIndex,pageSize);
            //3. 内容列表里的内容
            for(TitleMenuSection section: sections){
                if(StrUtil.isNotEmpty(section.getBgUrl())){
                    section.setBgUrl(imgPrefix + section.getBgUrl());
                }

                if(StrUtil.isNotEmpty(section.getTitleImgUrl())){
                    section.setTitleImgUrl(imgPrefix + section.getTitleImgUrl());
                }

                if(section.getShowType() == 0 || section.getShowType() == 4){
                    int column = section.getColumnCount();
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.eq("state",0);
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    for (TitleMenuSectionLinks links : linkss){
                        links.setIsOpen(section.getIsOpen());
                        links.setLinkUrl("/pages/product/detail/index?id=" + links.getLinkId());

                        String img_key = links.getImgUrl() != null ? links.getImgUrl() : "";
                        if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("https") < 0){
                            links.setImgUrl(imgPrefix + img_key);
                        }
//                链接的类型   product - 单商品 - page 商品页（title_menu_id）  group - 团购商品  coupon - 优惠券  image - 单图片 不跳转
                        if(links.getLinkType().equals("page")){//普通商品页
                            TitleMenu titleMenu = titleMenuMapper.selectById(links.getLinkId());
                            if(titleMenu != null){
                                img_key = titleMenu.getLinkLogo() != null ? titleMenu.getLinkLogo() : "";
                                if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("https") < 0){
                                    titleMenu.setLinkLogo(imgPrefix + img_key);
                                }
                            }
                        }else if(links.getLinkType().equals("product")){
                            Product product = productService.getProductInfoById(links.getLinkId(),1);
                            if(StrUtil.isEmpty(links.getImgUrl()) && links.getLinkId()!=null){
                                links.setImgUrl(product.getImage());
                            }
                            links.setProduct(product);
                        } else if(links.getLinkType().equals("coupons")){
                            Coupons coupons = couponsService.findById(links.getLinkId());
                            if(coupons!=null){
                                if(StrUtil.isEmpty(links.getImgUrl()) && links.getLinkId()!=null){
                                    coupons.setImgUrl(imgPrefix + coupons.getImgUrl());
                                    links.setImgUrl(coupons.getImgUrl());
                                }
                            }
                            links.setCoupons(coupons);
                        }

                        if(links.getLabelText() != null && !links.getLabelText().equals("")){
                            String[] lables = StringUtil.StrT0List(links.getLabelText(),",");
                            links.setLabelTexts(lables);
                        }
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                }
                else if(section.getShowType() == 1){// 子分类下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount() : 10;
                    List<Product> products = productService.queryProductList("",null,section.getCateChildId(),platform, 1, showCount);
                    section.setProducts(products);
                    int column = section.getColumnCount();
                    List<TitleMenuSectionLinks> linkss = new ArrayList<>();
                    for (Product product : products){
                        TitleMenuSectionLinks links = new TitleMenuSectionLinks();
                        links.setIsOpen(section.getIsOpen());
                        links.setLinkUrl("/pages/product/detail/index?id=" + product.getId());
                        links.setId(product.getId());
                        links.setLinkType("product");
                        if(links.getImgUrl() == null) {
                            if(StrUtil.isNotEmpty(product.getImage()) && product.getImage().indexOf("https") < 0){
                                links.setImgUrl(imgPrefix + product.getImage());
                            }else{
                                links.setImgUrl(product.getImage());
                            }
                        }
                        links.setProduct(product);

                        if(links.getLabelText() != null && !links.getLabelText().equals("")){
                            String[] lables = StringUtil.StrT0List(links.getLabelText(),",");
                            links.setLabelTexts(lables);
                        }
                        linkss.add(links);
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                } else if(section.getShowType() == 2){// 子分类下的商家列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():10;
                    //Integer cate_child_id, Integer offset, Integer pageSize, double longitude, double latitude
                    int offset = (pageIndex - 1) * pageSize;
                    List<Mer> mers = merService.selectBySection(section.getCateChildId(),offset, showCount,lng, lat);
                    section.setMers(mers);
                } else if(section.getShowType() == 3){// 单一商家下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():10;
                    List<Product> products = productService.queryProductList(section.getMerId(), showCount);
                    section.setProducts(products);
                } else if(section.getShowType() == 5){
                    int column = section.getColumnCount();
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.eq("state",0);
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    for (TitleMenuSectionLinks links : linkss){
                        links.setIsOpen(section.getIsOpen());
                        String img_key = links.getImgUrl() != null ? links.getImgUrl() : "";
//                        System.out.println("img_key: " + img_key);
                        if(StrUtil.isNotEmpty(links.getImgUrl()) && img_key.indexOf("https") < 0){
                            links.setImgUrl(imgPrefix + img_key);
                        }
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                }
                //全区域  或者限定当前用户的城市
                TitleMenuSectionCity sectionCity = sectionCityService.getSectionCityByCityName(section.getId(),user);
                if(section.getIsAllCity() == 1 || (sectionCity != null)){
                    sectionsShow.add(section);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sectionsShow;
    }


    @Override
    public List<TitleMenuSection> selectByMenuId(User user, Integer titleMenuId , String platform, Integer pageIndex , Integer pageSize) {
        try{
            //2. 内容列表
            QueryWrapper<TitleMenuSection> qw = new QueryWrapper<>();
            qw.eq("state",0);
            if(titleMenuId != null && titleMenuId > 0){
                qw.eq("title_menu_id",titleMenuId);
            }
            qw.orderByAsc("sort");
            List<TitleMenuSection> sectionsShow = new ArrayList<>();
            List<TitleMenuSection> sections = titleMenuSectionMapper.getPageEntityList(qw,pageIndex,pageSize);
            //3. 内容列表里的内容
            for(TitleMenuSection section: sections){

                if(StrUtil.isNotEmpty(section.getBgUrl())){
                    section.setBgUrl(imgPrefix + section.getBgUrl());
                }

                if(StrUtil.isNotEmpty(section.getTitleImgUrl())){
                    section.setTitleImgUrl(imgPrefix + section.getTitleImgUrl());
                }

                if(section.getShowType() == 0){
                    int column = section.getColumnCount();
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    for (TitleMenuSectionLinks links : linkss){
                        links.setIsOpen(section.getIsOpen());
                        // 拼团
                        if(links.getLinkType().equals("group")){
                            links.setLinkUrl("/pages/product/group/index?id=" + links.getLinkId());
                        }else{
                            links.setLinkUrl("/pages/product/detail/index?id=" + links.getLinkId());
                        }
                        String img_key = links.getImgUrl() != null ? links.getImgUrl() : "";
                        if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("http") < 0){
                            links.setImgUrl(imgPrefix + img_key);
                        }else{
                            if(links.getLinkId() != null){
                                Product product = productService.getProductInfoById(links.getLinkId(),1);
                                if(product!=null){
                                    links.setImgUrl(product.getImage());
                                }
                            }
                        }
//                链接的类型   product - 单商品 - page 商品页（title_menu_id）  group - 团购商品  coupon - 优惠券  image - 单图片 不跳转
                        if(links.getLinkType().equals("page")){//普通商品页
                            TitleMenu titleMenu = titleMenuMapper.selectById(links.getLinkId());
                            if(titleMenu != null){
                                img_key = titleMenu.getLinkLogo() != null ? titleMenu.getLinkLogo() : "";
                                if(StrUtil.isNotEmpty(img_key) && img_key.indexOf("http") < 0){
                                    titleMenu.setLinkLogo(imgPrefix + img_key);
                                }
                            }
                        } else if(links.getLinkType().equals("product")){
                            Product product = productService.getProductInfoById(links.getLinkId(),1);
                            links.setProduct(product);
                        }

                        if(links.getLabelText() != null && !links.getLabelText().equals("")){
                            String[] lables = StringUtil.StrT0List(links.getLabelText(),",");
                            links.setLabelTexts(lables);
                        }
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                } else if(section.getShowType() == 1){// 子分类下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount() : 20;
                    List<Product> products = productService.queryProductList("",null,section.getCateChildId(),platform, 1, showCount);
                    section.setProducts(products);
                    int column = section.getColumnCount();
                    List<TitleMenuSectionLinks> linkss = new ArrayList<>();
                    for (Product product : products){
                        TitleMenuSectionLinks links = new TitleMenuSectionLinks();
                        links.setIsOpen(section.getIsOpen());
                        links.setLinkUrl("/pages/product/detail/index?id=" + product.getId());
                        links.setLinkType("product");
                        links.setId(product.getId());
                        if(links.getImgUrl() == null) {
                            if(StrUtil.isNotEmpty(product.getImage()) && product.getImage().indexOf("https") < 0){
                                links.setImgUrl(imgPrefix + product.getImage());
                            }else{
                                links.setImgUrl(product.getImage());
                            }
                        }
                        links.setProduct(product);

                        if(links.getLabelText() != null && !links.getLabelText().equals("")){
                            String[] lables = StringUtil.StrT0List(links.getLabelText(),",");
                            links.setLabelTexts(lables);
                        }
                        linkss.add(links);
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                } else if(section.getShowType() == 2){// 子分类下的商家列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():20;
                    //Integer cate_child_id, Integer offset, Integer pageSize, double longitude, double latitude
                    int offset = (pageIndex - 1) * pageSize;
                    //Integer cate_child_id, Integer offset, Integer pageSize, double longitude, double latitude
                    List<Mer> mers = merService.selectBySection(section.getCateChildId(),offset, showCount,1, 1);
                    section.setMers(mers);
                } else if(section.getShowType() == 3){// 单一商家下的商品列表
                    int showCount = section.getShowCount() != null ? section.getShowCount():20;
                    List<Product> products = productService.queryProductList(section.getMerId(), showCount);
                    section.setProducts(products);
                } else if(section.getShowType() == 5){
                    int column = section.getColumnCount();
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.eq("state",0);
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    for (TitleMenuSectionLinks links : linkss){
                        links.setIsOpen(section.getIsOpen());
                        String img_key = links.getImgUrl() != null ? links.getImgUrl() : "";
//                        System.out.println("img_key: " + img_key);
                        if(StrUtil.isNotEmpty(links.getImgUrl()) && img_key.indexOf("https") < 0){
                            links.setImgUrl(imgPrefix + img_key);
                        }
                    }
                    List<List<TitleMenuSectionLinks>> table = ListUtil.splitList(linkss,column);
                    section.setTable(table);
                    section.setLinks(linkss);
                }else if(section.getShowType() == 6){//商品分类
                    QueryWrapper<TitleMenuSectionLinks> qw1 = new QueryWrapper<>();
                    qw1.eq("section_id",section.getId());
                    qw1.eq("state",0);
                    qw1.orderByAsc("sort");
                    List<TitleMenuSectionLinks> linkss = titleMenuSectionLinksMapper.selectList(qw1);
                    section.setLinks(linkss);
                }
                //全区域  或者限定当前用户的城市
                TitleMenuSectionCity sectionCity = sectionCityService.getSectionCityByCityName(section.getId(),user);
                if(section.getIsAllCity() == 1 || (sectionCity != null)){
                    sectionsShow.add(section);
                }
            }
            return sectionsShow;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
